package com.blog.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: XieLiKui
 * @Description:在缓存中查询是否已经有访问记录
 **/

@Component
public class FindRequestCacheUtil {

    @Autowired
    private RedisUtil redisUtil;

    public boolean findCache(int redisDbNum , int reqId , String reqIp){
        redisUtil.setDataBase(redisDbNum); //设置保存到哪个数据库
        List<Object> ipForArticleList = redisUtil.lGet(reqIp, 0, -1);  //根据ip查询是否有值
        //没有值，则添加
        if(ipForArticleList.size() == 0){
            ipForArticleList.add(reqId);
            redisUtil.lSet(reqIp,ipForArticleList);
            return true;
            //有值，在遍历集合
        }else {
            boolean flag = true;    //标识
            for(Object id : ipForArticleList){   //对比是否有值
                if ((int) id == reqId) {    //如果存在，改变标识
                    flag = false;
                    break;
                }
            }
            //根据标识true,则保存至数据库
            if(flag){
                redisUtil.lSet(reqIp,reqId);
            }
            return flag;
        }
    }
}
